//
//  PDFViewVC.m
//  断点下载PDF
//
//  Created by 徐凯 on 16/5/3.
//  Copyright © 2016年 cqjtu. All rights reserved.
//

#import "PDFViewVC.h"
#import "WHCNetWorkKit.h"
#import "WHC_DownloadObject.h"
#import "UIView+WHC_Toast.h"
#import "UIView+WHC_Loading.h"
#import "UIScrollView+WHC_PullRefresh.h"
#import "OffLinePDFVC.h"
#import "AppDelegate.h"
#import "DateTimeUtil.h"
#import "WebViewVC.h"
@interface PDFViewVC ()
@property(strong,nonatomic) NSMutableArray* downloadObjectArr;
@end

@implementation PDFViewVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initUI];
}
-(void)initUI{
    //[self.navigationController  setToolbarHidden:NO animated:YES];

    self.pdfWebView = [[WKWebView alloc]init];
    self.pdfWebView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    _pdfWebView.backgroundColor = [UIColor whiteColor];
    self.view .backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.pdfWebView.navigationDelegate = self;
    self.navigationItem.title = @"PDF阅读";
    self.pdfWebView.UIDelegate = self;
    self.pdfWebView.scrollView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:_pdfWebView];
   
    
    //self.pdfWebView.allowsBackForwardNavigationGestures =YES;
    
    [self initData];
    if(![_fileName isEqualToString:@""]){
        dispatch_async(dispatch_get_main_queue(),^{
//            NSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
           // NSString* filePath = [paths objectAtIndex:0];
            NSString* filePath = [WHC_DownloadObject pdfDirectory];
            NSString* fileName = _fileName;
            NSString *path = [filePath stringByAppendingPathComponent:fileName];
            BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
            if (fileExists) {
                NSData *data = [NSData dataWithContentsOfFile:path];
                [self.pdfWebView loadData:data MIMEType:@"application/pdf" characterEncodingName:@"UTF-8" baseURL:nil];
            }
        });

    }
    else if(![_fileUrl isEqualToString:@""]){
        NSURL* url = [NSURL URLWithString:_fileUrl];
        NSURLRequest* request = [NSURLRequest requestWithURL:url];
        [self.pdfWebView loadRequest:request];
        UIBarButtonItem* rightBtn = [[UIBarButtonItem alloc]initWithTitle:@"下载" style:UIBarButtonItemStyleDone target:self action:@selector(downLoad)];
        self.navigationItem.rightBarButtonItem = rightBtn;
        
           }
    UIBarButtonItem* leftBtn = [[UIBarButtonItem alloc]initWithTitle:@"下载中心" style:UIBarButtonItemStyleDone target:self action:@selector(leftPad)];
    self.navigationItem.leftBarButtonItem = leftBtn;

}
-(void)leftPad{
    
        //OffLinePDFVC* vc = [[OffLinePDFVC alloc] init];
       WebViewVC* vc = [[WebViewVC alloc] init];
       [self.navigationController pushViewController:vc animated:YES];
    //self.navigationItem.rightBarButtonItem = nil;
}
- (void)initData{
    _downloadObjectArr = [NSMutableArray arrayWithArray:[WHC_DownloadObject readDiskAllCache]];
    if(![_fileUrl isEqualToString:@""]){
        
        for(int i = 0 ;i<_downloadObjectArr.count;i++){
        WHC_DownloadObject * downloadObject = _downloadObjectArr[i];
            if([downloadObject.downloadPath isEqualToString:_fileUrl]&&downloadObject.downloadState== WHCDownloadCompleted){
                _fileName = downloadObject.fileName;
            }
        
    }
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark--- UIWkWebViewNavigationDelegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { // 类
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { // 类似
    if (webView.title.length > 0) {
        self.title = webView.title;
    }
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    
    decisionHandler(WKNavigationResponsePolicyAllow);
}


- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    
    
    //NSString *url = [navigationAction.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    
    decisionHandler(WKNavigationActionPolicyAllow);
    
}
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
    
}


#pragma mark- download pdf
-(void)downLoad{
    
    __weak typeof(self) weakSelf = self;
    NSString* fileName = [self.fileUrl componentsSeparatedByString:@"/"].lastObject;
    #if WHC_BackgroundDownload
    [[WHC_SessionDownloadManager shared] setBundleIdentifier:@"com.WHC.WHCNetWorkKit.backgroundsession"];
    WHC_DownloadSessionTask * downloadTask = [[WHC_SessionDownloadManager shared]
                                              download:self.fileUrl
                                              savePath:[WHC_DownloadObject pdfDirectory]
                                              saveFileName:fileName
                                              response:^(WHC_BaseOperation *operation, NSError *error, BOOL isOK) {
                                                  [weakSelf.view toast:@"已经添加到下载队列"];
                                                  WHC_DownloadOperation * downloadOperation = (WHC_DownloadOperation*)operation;
                                                  WHC_DownloadObject * downloadObject = [WHC_DownloadObject new];
                                                  downloadObject.fileName = downloadOperation.saveFileName;
                                                  downloadObject.downloadPath = downloadOperation.strUrl;
                                                  downloadObject.downloadState = WHCDownloading;
                                                  downloadObject.currentDownloadLenght = downloadOperation.recvDataLenght;
                                                  downloadObject.totalLenght = downloadOperation.fileTotalLenght;
                                                  [downloadObject writeDiskCache];
                                              } process:^(WHC_BaseOperation *operation, uint64_t recvLength, uint64_t totalLength, NSString *speed) {
                                                  NSLog(@"recvLength = %llu , totalLength = %llu , speed = %@",recvLength , totalLength , speed);
                                              } didFinished:^(WHC_BaseOperation *operation, NSData *data, NSError *error, BOOL isSuccess) {
                                                  if (isSuccess) {
                                                      [weakSelf.view toast:@"下载成功"];
                                                      [weakSelf saveDownloadStateOperation:(WHC_DownloadOperation *)operation];
                                                  }else {
                                                      [weakSelf.view toast:error.userInfo[NSLocalizedDescriptionKey]];
                                                      if (error != nil &&
                                                          error.code == WHCCancelDownloadError) {
                                                          [weakSelf saveDownloadStateOperation:(WHC_DownloadOperation *)operation];
                                                      }
                                                  }
                                              }];
#else
    WHC_DownloadOperation * downloadTask = nil;
    downloadTask = [[WHC_HttpManager shared] download:self.fileUrl
                                             savePath:[WHC_DownloadObject pdfDirectory]
                                         saveFileName:fileName
                                             response:^(WHC_BaseOperation *operation, NSError *error, BOOL isOK) {
                                                 if (isOK) {
                                                     
                                                     WHC_DownloadOperation * downloadOperation = (WHC_DownloadOperation*)operation;
                                                     WHC_DownloadObject * downloadObject = [WHC_DownloadObject readDiskCache:operation.strUrl];
                                                     if (downloadObject == nil) {
                                                         [weakSelf.view toast:@"已经添加到下载队列"];
                                                         

                                                         downloadObject = [WHC_DownloadObject new];
                                                     }
                                                     downloadObject.fileName = downloadOperation.saveFileName;
                                                     downloadObject.downloadPath = downloadOperation.strUrl;
                                                     downloadObject.downloadState = WHCDownloading;
                                                     downloadObject.currentDownloadLenght = downloadOperation.recvDataLenght;
                                                     downloadObject.totalLenght = downloadOperation.fileTotalLenght;
                                                     [downloadObject writeDiskCache];
                                                 }else {
                                                     [weakSelf errorHandle:(WHC_DownloadOperation *)operation error:error];
                                                 }
                                             } process:^(WHC_BaseOperation *operation, uint64_t recvLength, uint64_t totalLength, NSString *speed) {
                                                 NSLog(@"recvLength = %llu totalLength = %llu speed = %@",recvLength , totalLength , speed);
                                                 NSLog(@"正在下下载中。。。。。。。。。。。。。。。。。。");
                                             } didFinished:^(WHC_BaseOperation *operation, NSData *data, NSError *error, BOOL isSuccess) {
                                                 if (isSuccess) {
                                                    [weakSelf.view toast:@"下载成功"];
                                                     NSLog(@"下载完成 请注意保存");
                                                     [weakSelf saveDownloadStateOperation:(WHC_DownloadOperation *)operation];
                                                 }else {
                                                     [weakSelf errorHandle:(WHC_DownloadOperation *)operation error:error];
                                                     if (error != nil &&
                                                         error.code == WHCCancelDownloadError) {
                                                         [weakSelf saveDownloadStateOperation:(WHC_DownloadOperation *)operation];
                                                     }
                                                 }
                                             }];
    
#endif

    if (downloadTask.requestStatus == WHCHttpRequestNone) {
#if WHC_BackgroundDownload
        if (![[WHC_SessionDownloadManager shared] waitingDownload]) {
            return;
        }
#else
        if (![[WHC_HttpManager shared] waitingDownload]) {
            return;
        }
#endif
        WHC_DownloadObject * downloadObject = [WHC_DownloadObject readDiskCache:downloadTask.strUrl];
        if (downloadObject == nil) {
            [weakSelf.view toast:@"已经添加到下载队列"];
            downloadObject = [WHC_DownloadObject new];
        }
        downloadObject.fileName = fileName;
        downloadObject.downloadPath = self.fileUrl;
        downloadObject.downloadState = WHCDownloadWaitting;
        downloadObject.currentDownloadLenght = 0;
        downloadObject.totalLenght = 0;
        [downloadObject writeDiskCache];
     }

    
}
- (void)saveDownloadStateOperation:(WHC_DownloadOperation *)operation {
    WHC_DownloadObject * downloadObject = [WHC_DownloadObject readDiskCache:operation.saveFileName];
    if (downloadObject != nil) {
        downloadObject.currentDownloadLenght = operation.recvDataLenght;
        downloadObject.totalLenght = operation.fileTotalLenght;
        downloadObject.downloadTimeString = [DateTimeUtil currentDataTime:@"YYYY-MM-dd HH:mm:ss"];
        [downloadObject writeDiskCache];
    }
}
- (void) errorHandle:(WHC_DownloadOperation *)operation error:(NSError *)error {
    NSString * errInfo = error.userInfo[NSLocalizedDescriptionKey];
    if ([errInfo containsString:@"404"]) {
        [self.view toast:@"该文件不存在"];
        WHC_DownloadObject * downloadObject = [WHC_DownloadObject readDiskCache:operation.strUrl];
        if (downloadObject != nil) {
            [downloadObject removeFromDisk];
        }
    }else {
        if ([errInfo containsString:@"已经在下载中"]) {
            {
                [self.view toast:errInfo];
                self.navigationController.navigationItem.rightBarButtonItem = nil;
                
            }
        }else {
            [self.view toast:@"下载失败"];
            NSLog(@"errInfo:%@",errInfo);
        }
    }
}

@end
